<template>
  <div class="login">
    <el-card class="login-card">
      <div class="title">EZOps 管理平台</div>
      <el-form :model="loginForm" :rules="loginFormRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input
            prefix-icon="UserFilled"
            v-model.trim="loginForm.username"
            maxlength="32"
            placeholder="请输入账号"
            clearable
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            prefix-icon="Lock"
            v-model.trim="loginForm.password"
            maxlength="16"
            placeholder="请输入密码"
            clearable
            show-password
          />
        </el-form-item>

        <el-form-item style="width: 100%">
          <el-button
            type="primary"
            size="default"
            style="width: 100%; border-radius: 2px"
            :loading="loginLoading"
            @click="handleLogin"
          >
            <span v-if="!loginLoading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const loginFormRef = ref(null)
const loginLoading = ref(false)

const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

const loginFormRules = {
  username: [
    { required: true, message: '请填写用户名', trigger: 'change' },
    { min: 3, message: '用户名长度应不小于3个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请填写密码', trigger: 'change' },
    { min: 5, message: '密码长度应不小于5个字符', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) {
    console.log('登录表单引用不存在');
    return;
  }

  try {
    const valid = await loginFormRef.value.validate();
    if (!valid) {
      console.log('表单验证失败');
      return;
    }

    console.log('开始登录，表单数据：', loginForm);
    loginLoading.value = true;
    const response = await userStore.login(loginForm);
    console.log('登录响应数据：', response);
    
    // 判断是否成功获取到token
    if (response && response.data && response.data.token) {
      console.log('成功获取token：', response.data.token.substring(0, 30) + '...');
      // 获取用户信息
      console.log('开始获取用户信息...');
      await userStore.getUserInfo();
      
      // 确保用户信息已经获取到
      if (userStore.userInfo) {
        console.log('用户信息获取成功：', userStore.userInfo);
        ElMessage.success('登录成功');
        router.push('/dashboard');
      } else {
        console.error('获取用户信息失败：userInfo为空');
        throw new Error('获取用户信息失败');
      }
    } else {
      console.error('登录响应数据异常：', response);
      throw new Error('登录失败：未获取到有效token');
    }
  } catch (error) {
    console.error('登录过程发生错误：', error);
    ElMessage.error(error.message || '登录失败');
  } finally {
    loginLoading.value = false;
  }
}
</script>

<style scoped>
.login {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
}

.title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 30px;
  color: #333;
}
</style>